package com.qf.action;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.qf.base.BaseServlet;
import com.qf.model.Cart;
import com.qf.model.CartItem;
import com.qf.model.OrderItem;
import com.qf.model.Orders;
import com.qf.model.User;
import com.qf.utils.CommonsUtils;



/**
 * Servlet implementation class OrderServlet
 */
public class OrderServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
  /**
   * 生成订单页面
  * @author: 千锋
  * @createTime: 2017年7月5日 下午3:01:02
  * @history:
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException void
 * @throws SQLException 
   */
	protected void createOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		String receiverAddress = request.getParameter("receiverAddress");
		String receiverName = request.getParameter("receiverName");
		String receiverPhone = request.getParameter("receiverPhone");
		HttpSession session = request.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		if(cart!=null){//购物车有东西
		Orders o=new Orders();
		o.setAddress(receiverAddress);
		o.setOid(CommonsUtils.getUUID());
		o.setOrdertime(new Date());
		o.setState(0);
		o.setTelephone(receiverPhone);
		o.setUser((User)session.getAttribute("user"));
		o.setTotal(cart.getTotal());	
		o.setName(receiverName);
		
		
		
		//订单项
		Map<String, CartItem> cartItems = cart.getCartItem();

		Set<Entry<String, CartItem>> entrySet = cartItems.entrySet();
		
		for(Map.Entry<String, CartItem> e: entrySet){
			CartItem cartItem = e.getValue();//购物项
			OrderItem item=new OrderItem();//订单项
			item.setCount(cartItem.getBuyNum());
			item.setItemid(CommonsUtils.getUUID());
			item.setProduct(cartItem.getProduct());
			item.setSubtotal(cartItem.getSubTotal());
			item.setOrders(o);
			o.getList().add(item);
			}
			//生成订单
		/**
		 * 订单表和订单项表存储数据
		 */
			boolean falg= orderServiceImpl.add(o);
		
		if(falg){
			//清空购物车
			session.removeAttribute("cart");
			response.getWriter().write("<script type='text/javascript'>alert('生成订单成功');window.location.href='index.jsp';</script>");
			
		}
		
		
		
		}else{//购物车空
			response.getWriter().write("<script type='text/javascript'>alert('购物车为空，请先去购物');window.location.href='index.jsp';</script>");

		}
		
	}
}
